package com.hethongviet.job.helpers;


import com.hethongviet.job.AppMain;

import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

public class MyLocationWithCriteria
{
	private LocationManager locationManager;
	private LocationResult locationResult;
	//private boolean isGPSEnabled = false;
	
	public MyLocationWithCriteria()
	{
	}
	
	public boolean getLocation(Context context, LocationResult result)
	{
		// I use LocationResult callback class to pass location value from
		// MyLocation to user code.
		locationResult = result;
		if (locationManager == null) locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

		// exceptions will be thrown if provider is not permitted.
//		try
//		{
//			isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
//		} catch (Exception ex)
//		{
//			ex.printStackTrace();
//		}
//		
//		// don't start listeners if no provider is enabled
//		if (!isGPSEnabled) return false;
//
//		if (isGPSEnabled) locationManager.requestLocationUpdates(
//				LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
		
		Criteria criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_FINE);
		criteria.setAltitudeRequired(false);
		criteria.setBearingRequired(false);
		criteria.setCostAllowed(true);
		criteria.setPowerRequirement(Criteria.POWER_LOW);
		
		String providerName = locationManager.getBestProvider(criteria, true);
		
		if(providerName != null) 
		{
			locationResult.gotLocation(locationManager.getLastKnownLocation(providerName));
		}
		
		locationManager.requestLocationUpdates(providerName, 1000, 1, locationListenerGps);
		
		return true;
	}

	private final LocationListener locationListenerGps = new LocationListener() {
		public void onLocationChanged(Location location)
		{
			AppMain.debug("GPS location change!!!!");
			locationResult.gotLocation(location);
		}

		public void onProviderDisabled(String provider)
		{
		}

		public void onProviderEnabled(String provider)
		{
		}

		public void onStatusChanged(String provider, int status, Bundle extras)
		{
		}
	};

	public void stop()
	{
		locationManager.removeUpdates(locationListenerGps);
	}


	public static abstract class LocationResult
	{
		public abstract void gotLocation(Location location);
	}
}
